import AudioTool from "../Framework/scripts/AudioTool";
import Watcher from "../Framework/scripts/Watcher";
import GameAssetMgr from "./GameAssetMgr";
import ItemPanel from "./ItemPanel";
const { ccclass, property } = cc._decorator;

@ccclass
export default class Item extends cc.Component {

    @property(cc.Sprite)
    icon: cc.Sprite = null;

    public layer = 0;
    public coord:{x,y} = null;


    private _interaction = true;
    public get interaction(){return this._interaction;}
    public set interaction(v:boolean){
        this._interaction = v;
        // this.icon.setMaterial(0,!v ? cc.Material['getBuiltinMaterial']('2d-gray-sprite'): cc.Material['getBuiltinMaterial']('2d-sprite'));
        
        let normalColor = new cc.Color();
        normalColor.fromHEX('#FFFFFF');
        let grayColor = new cc.Color();
        grayColor.fromHEX('#AC8D8D');
        
        this.node.color = v ? normalColor : grayColor;
        this.icon.node.color = this.node.color;
    }

    onLoad() {
        const context = this;
        let onEnter = () => {
            if (context.node.scale == 1.2 ||　!context._interaction ) return;
            cc.tween(context.node).to(0.2, { scale: 1.2 }, cc.easeBackOut()).start();
            context.node.zIndex = this.node.parent.childrenCount + 1;
        };
        let onLeave = () => {
            if (context.node.scale == 1||!context._interaction) return;
            cc.tween(context.node).to(0.2, { scale: 1 }, cc.easeBackOut()).start();
            context.node.zIndex = 1;
        };
        let onExit = ( e ) => {

            if(!context._interaction)return;

            context.node.zIndex = 1;
            context.Click();

            context.node.off(cc.Node.EventType.TOUCH_START);
            context.node.off(cc.Node.EventType.MOUSE_ENTER);
            context.node.off(cc.Node.EventType.MOUSE_UP);
            context.node.off(cc.Node.EventType.TOUCH_END);
            context.node.off(cc.Node.EventType.MOUSE_LEAVE);
            context.node.off(cc.Node.EventType.TOUCH_CANCEL);

            //console.log(e);
            //return false;
        };
        this.node.on(cc.Node.EventType.TOUCH_START, onEnter, this);
        //this.node.on(cc.Node.EventType.MOUSE_ENTER, onEnter, this);
        //this.node.on(cc.Node.EventType.MOUSE_LEAVE, onLeave, this);
        this.node.on(cc.Node.EventType.TOUCH_CANCEL, onLeave, this);
        //this.node.on(cc.Node.EventType.MOUSE_UP, onExit, this);
        this.node.on(cc.Node.EventType.TOUCH_END, onExit, this);
    }

    gid = 0;
    setIcon(gid) {
        this.gid = gid;
        let name = `0${gid}`;
        this.icon.spriteFrame = GameAssetMgr.instance.getSpriteByID(name);
    }

    Click() {
        AudioTool.instance.play('click');
        Watcher.dispatch(ItemPanel.EVENT_FLY_ITEM, this);
    }

}
